﻿using CommunicationProtocol.dto.command.server;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;
using CommunicationProtocol.dto;
using Microsoft.Xna.Framework.Input;
using monoClient.utils;
using CommunicationProtocol.dto.command.client;
using Microsoft.Extensions.Logging;
using static CommunicationProtocol.utils.PixelsLocationToColumnRowTransformer;
namespace monoClient.renderer
{
    internal class FollowingMousePictureRenderer : CommandExecutor
    {
        private PlantBuyableStatusResp command;

        ConcurrentDictionary<CommandExecutor, object> commandExecutors;

        Rectangle location;

        Texture2D plantTexture2D;

        ILogger logger;

        int status = 0;


        public FollowingMousePictureRenderer(PlantBuyableStatusResp command,
            ConcurrentDictionary<CommandExecutor, object> commandExecutors)
        {
            this.command = command;
            this.commandExecutors = commandExecutors;

            logger = LoggerFactoryUtil.CreateLogger(nameof(FollowingMousePictureRenderer));

            foreach (CommandExecutor executor in commandExecutors.Keys)
            {
                if (executor is BuyablePlantRenderer)
                {
                    BuyablePlantRenderer buyablePlantRenderer = (BuyablePlantRenderer) executor;

                    if (!Equals(buyablePlantRenderer.StaticPlant.ObjectId, command.objectId))
                    {
                        continue;
                    }

                    Rectangle initPlantLocation = buyablePlantRenderer.plantLocation;
                    location = new Rectangle(
                        initPlantLocation.Location.X,
                        initPlantLocation.Location.Y,
                        initPlantLocation.Size.X,
                        initPlantLocation.Size.Y
                    );
                    plantTexture2D = buyablePlantRenderer.plantTexture2D;
                    break;
                }
            }

            if (plantTexture2D is null)
            {
                throw new ArgumentException("未找到要种植的植物" + command);
            }
            
            OutBandHolder.send(new OtherPlayerPlantingCommand(
                command.objectId,
                1
                
            ));
        }

        public void Draw(GameTime gameTime, SpriteBatch _spriteBatch)
        {
            if (status == 0)
            {
                _spriteBatch.Draw(plantTexture2D, location, Color.White);
            }
        }


        public void Update(GameTime gameTime, MouseState mouseState, MouseState oldMouseState)
        {
            int x = mouseState.Position.X;
            int y = mouseState.Position.Y;
            if (status == 0)
            {
                /*选中的植物跟随鼠标移动*/

                x -= (location.Size.X / 2);


                y -= location.Size.Y / 2;

                location.Location = new Point(x, y);

                Task.Run(() =>
                {
                    
                    OutBandHolder.send(new OtherPlayerPlantingCommand(
                        command.objectId,
                        x,
                        y
                        ));
                });
                
            }

            if (status == 0 && mouseState.LeftButton != ButtonState.Pressed &&
                oldMouseState.LeftButton == ButtonState.Pressed)
            {
                /*左键点击，要求向服务器发起种植植物请求*/


                if (status == 0)
                {
                    status = 1;
                }
                else
                {
                    return;
                }

                /*bool lockTaken = false;
                
                try
                {
                    Monitor.Enter(statusLock, ref lockTaken);
                    if (status == 0)
                    {
                        status = 1;
                    }
                    else
                    {
                        return;
                    }

                }
                finally
                {
                    if (lockTaken) { 
                        Monitor.Exit(statusLock);
                    }
                }*/


                if (isOnLawn(x,y,out int column,out int row)){
                    // 鼠标点击的地方在可以种植植物的草坪上    
                    Debug.WriteLine($"点击了{row}行{column}列 原像素是{x},{y}");

                    OutBandHolder.send(
                        new PlantAPlant(command.objectId, column, row)
                    );


                   
                }

                if (commandExecutors.TryRemove(this, out object val))
                {
                    Task.Run(() =>
                    {

                        OutBandHolder.send(new OtherPlayerPlantingCommand(
                            command.objectId,
                            3
                            ));
                    });
                    Debug.WriteLine("删除成功" + this);
                }
            }
        }
    }
}